package inglar.autotc.client.ui;

import inglar.autotc.client.Utilities;
import inglar.autotc.client.resource.ResourceHandler;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class PageWelcome extends Composite {
	
	private VerticalPanel contentPanel;
	private VerticalPanel variableContent;
	private HTMLPanel htmlUserHeader;
	private HTMLPanel htmlUserFooter;
	
	/**
	 * @wbp.parser.constructor
	 */
	public PageWelcome() {
		
		contentPanel = new VerticalPanel();
		initWidget(contentPanel);
		
		htmlUserHeader = new HTMLPanel(ResourceHandler.INSTANCE.userHeader().getText());
		contentPanel.add(htmlUserHeader);
		
		variableContent = new VerticalPanel();
		contentPanel.add(variableContent);
		
		htmlUserFooter = new HTMLPanel(ResourceHandler.INSTANCE.userFooter().getText());
		contentPanel.add(htmlUserFooter);
		
	}
	
	public PageWelcome(String message) {
		this();
		
		if(message.isEmpty()) {
			if(Utilities.isLogged()) {
				showLogged();
			} else {
				showUnlogged();
			}
		} else {
			showInstallationError(message);
		}
	}
	
	private void showLogged() {
		variableContent.clear();
		
		HTML welcome = new HTML("<h3 style='color: green; font-weight: bold;'>" +
				"Hello, " + Cookies.getCookie("QN") + "!<h3><br/>" +
				"New user? Please see the the " +
				"<a href='manual.html'>user manual</a> for directions." +
				"<br/><br/>");
		
		variableContent.add(welcome);
		
		Button logout = new Button("Log out");
		logout.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				Utilities.logout();
			}
		});
		variableContent.add(logout);
	}
	
	private void showUnlogged() {
		variableContent.clear();
		variableContent.add(new HTMLPanel(ResourceHandler.INSTANCE.userNotLogged().getText()));
		new DialogBoxLogin().center();
	}
	
	private void showInstallationError(String message) {
		variableContent.clear();
		VerticalPanel _t = new VerticalPanel();
		_t.add(new HTMLPanel(
				"<br/>" +
				"<span style='font-weight: bold;'>You may not have installed AutoTC correctly.</span><br/>" +
				"<br/>" +
				"This webapp has checked the system and found the following error:<br/>" +
				"<span style='color: red; font-weight: bold;'>" + message + "</span><br/>" +
				"<br/>" +
				"Please check the manual to resolve the problem.<br/>"
				));
		variableContent.add(_t);
	}
}
